import collections
import datetime
import time

from django.db.models import Count
from django.http import JsonResponse
from django.shortcuts import render

from web import models


def dashboard(request, project_id):
    """概览"""
    # 1. 问题状态
    # 有序字典
    status_dict = collections.OrderedDict()
    for k, v in models.Issues.status_choices:
        status_dict[k] = {'v': v, 'count': 0}

    # 分组
    issues_data = models.Issues.objects.filter(project_id=project_id).values('status').annotate(ct=Count('id'))
    for item in issues_data:
        status_dict[item['status']]['count'] = item['ct']

    # 2. 项目成员
    user_list = models.Participant.objects.filter(project_id=project_id).values_list('user_id', 'user__name')

    # 3. 最近10个动态
    top_ten = models.Issues.objects.filter(project_id=project_id, assign__isnull=False).order_by('-id')[:10]
    context = {
        'status_dict': status_dict,
        'user_list': user_list,
        'top_ten': top_ten,
    }

    return render(request, 'dashboard.html', context)


def issues_chart(request, project_id):
    """概览折线图"""

    """
        构造数据
        {
            2020-09-1: [时间戳, 0],
            ...
        }
    """
    today = datetime.datetime.now().date()
    date_dict = collections.OrderedDict()
    for i in range(0, 30):
        date = today - datetime.timedelta(days=i)
        date_dict[date.strftime('%Y-%m-%d')] = [time.mktime(date.timetuple()) * 1000, 0]

    # 近30天创建的问题数量
    # 后面extra...相当于：select id, name, DATE_FORMAT(web_issues.create_datetime, "%%Y-%%m-%%d") as ctime from web_issues
    res = models.Issues.objects.filter(project_id=project_id,
                                       create_datetime__gte=today - datetime.timedelta(days=30)
                                       ).extra(
        select={'ctime': 'DATE_FORMAT(web_issues.create_datetime, "%%Y-%%m-%%d")'}
    ).values('ctime').annotate(ct=Count('id'))

    for item in res:
        date_dict[item['ctime']][1] = item['ct']

    return JsonResponse({'status': True, 'data': list(date_dict.values())})
